package com.wang.tx.mysql;

import com.alibaba.fastjson.JSONArray;
import com.wang.tx.core.TccCallback;
import com.wang.tx.core.TccTransaction;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

public class MySqlTccCallback extends TccCallback {
    public static final String update = "update tcc_transaction_info set state = ? where id = ?";
    public static final String updateFail = "update tcc_transaction_info set state = ?, has_try_list = ? where id = ?";

    public static PreparedStatement updateSql = null;
    public static PreparedStatement updateFailSql = null;

    private long id;

    public MySqlTccCallback(long id) {
        this.id = id;
    }

    @Override
    public void trySuccess() {
        try {
            updateSql.setInt(1, TRY_OK);
            updateSql.setLong(2, this.id);
            updateSql.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void tryFail(List<TccTransaction> hasTry) {
        List<Long> list = hasTry.stream().map(TccTransaction::id).collect(Collectors.toList());
        String s = JSONArray.toJSONString(list);
        try {
            updateFailSql.setInt(1, TRY_FAIL);
            updateFailSql.setString(2, s);
            updateFailSql.setLong(3, this.id);
            updateFailSql.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void txSuccess() {
        try {
            updateSql.setInt(1, SUCCESS);
            updateSql.setLong(2, this.id);
            updateSql.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void txFail() {
        try {
            updateSql.setInt(1, FAIL);
            updateSql.setLong(2, this.id);
            updateSql.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
